package org.shopen.puremvc.model
{
	import mx.rpc.http.mxml.HTTPService;
	
	import org.puremvc.as3.patterns.proxy.Proxy;
	import org.shopen.puremvc.model.utils.CompleteDelegate;

	public class ToolboxProxy extends Proxy
	{
		public static const NAME : String = "ToolboxProxy";
		public static const TOOLS_LOADED : String = NAME + "." + "TOOLS_LOADED";
		public static const TOOLS_LOAD_FAILED : String = NAME + "." + "TOOLS_LOAD_FAILED";
		
		protected var service : HTTPService;
		protected var completeDelegate : CompleteDelegate = null;
		
		
		public function ToolboxProxy(data:Object=null)
		{
			super(ToolboxProxy.NAME, data);
		}
		
		override public function getProxyName():String
		{
			return ToolboxProxy.NAME;
		}
		
		
		override public function onRegister():void
		{
			setService();
		}
			
		private function setService() : void
		{
			service = new HTTPService();
			service.resultFormat = "e4x";
			service.addEventListener(ResultEvent.RESULT, serviceResultListener);
			service.addEventListener(FaultEvent.FAULT, serviceFaultListener);
		}
		
		private function serviceResultListener(event : ResultEvent) : void
		{
			var dataXML : XML = event.result as XML;
			setData(dataXML);
			sendResult();
			sendCompleteEvent();
		}
		
		private function sendResult() : void
		{
			sendNotification(ManifestProxy.MANIFEST_LOADED, manifestXML);
			sendNotification(ManifestProxy.ORGANIZATION_META_AVAILABLE, organizationMeta);
		}
		
		private function serviceFaultListener(event : FaultEvent) : void
		{
			sendNotification(ManifestProxy.MANIFEST_LOAD_FAILED, event.message.toString());
		}
		
		private function sendCompleteEvent() : void
		{
			if (completeDelegate != null)
			{
				completeDelegate.dispatchComplete();
			}
		}
		
		public function loadData(url : String, completeDelegate : CompleteDelegate = null) : void
		{
			this.completeDelegate = completeDelegate;
			if (isDataLoaded && service.url == url)
			{
				sendResult();
				sendCompleteEvent();
			}
			else
			{
				service.url = url;
				service.send();
			}
		}
		
		public function get isDataLoaded() : Boolean
		{
			var result : Boolean = getData() != null;
			return result;
		}
	}
}